<template>
  <el-dialog
    :model-value="visible"
    title="通过邀请码加入题目集"
    width="400px"
    @update:model-value="$emit('update:visible', $event)"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="邀请码" prop="inviteCode">
        <el-input 
          v-model="form.inviteCode" 
          placeholder="请输入邀请码（支持永久/临时邀请码）" 
          maxlength="20" 
          show-word-limit 
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">加入</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from "vue";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  loading: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:visible', 'submit']);

const formRef = ref(null);
const form = reactive({
  inviteCode: ""
});

const rules = {
  inviteCode: [
    { required: true, message: "请输入邀请码", trigger: "blur" },
    { min: 8, max: 20, message: "邀请码格式不正确", trigger: "blur" }
  ]
};

watch(() => props.visible, (val) => {
  if (!val) {
    form.inviteCode = "";
    formRef.value?.resetFields();
  }
});

const handleClose = () => {
  emit('update:visible', false);
};

const handleSubmit = async () => {
  const valid = await formRef.value.validate();
  if (valid) {
    emit('submit', form.inviteCode);
  }
};
</script>
